import {Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy, ViewChild, OnDestroy} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {CrowdService} from "@crowd/crowd.service";

import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {ToolsService} from "@shared/service/tools/tools.service";
import {Subject} from "rxjs";
import {ImageServeService} from "@shared/service/image/image-serve.service.ts";
import {CrowdDynamicRespVO} from "@interface/index";


@Component({
  selector: 'dynamic-manage',
  templateUrl: './dynamic-manage.component.html',
  styleUrls: ['./dynamic-manage.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class DynamicManageComponent implements OnInit, OnDestroy {

  @ViewChild(SeedInfiniteScroll) infiniteScroll;

  public chooseId: number;
  public ngUnsubscrible: any;
  public crowdCode: string;
  public id: number;
  public index: number;
  public delPic = '../../../assets/icon/crowd-del.png';
  public params: any = {
    'crowdCode': '',
    'page': 1,
    'rows': 10
  };

  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public dynamicList: Array<CrowdDynamicRespVO> = [];
  public dynamic: CrowdDynamicRespVO;

  constructor(public route: ActivatedRoute,
              public router: Router,
              public imgSer: ImageServeService,
              public crowdService: CrowdService,
              private toolsService: ToolsService
  ) {
    this.route.queryParams.subscribe(params => {
      this.params.crowdCode = params['crowdCode'];
      this.getCrowdDynamics();
    });
  }

  // 获取活动动态列表
  getCrowdDynamics() {
    this.ngUnsubscrible = this.crowdService.getCrowdDynamics(this.params).subscribe(res => {
      if (res.result === '0' && res.data && res.data.list.length > 0) {
        this.params['page']++;
        this.infiniteScroll.complete();
        if (res.data.hasNextPage === false) {
          this.infiniteScroll.enable(false);
        }
        this.dynamicList = [...this.dynamicList, ...res.data.list];
      }
    });
  }

  // 删除动态时触发弹框，是否删除
  deleteDynamic(id: number) {
    this.chooseId = id;
    this.toolsService.presentConfirm('确定删除？', 1, '', this.delDynamic.bind(this), '是', '否');
  }

  // 删除某一条动态
  delDynamic() {
    this.crowdService.delCrowdDynamics(this.chooseId).subscribe(res => {
      if (res.result === '0') {
        this.dynamicList = this.dynamicList.filter(dynamic => dynamic.id !== this.chooseId);
      } else {
        this.toolsService.showToast(res.msg);
      }
    });

    this.toolsService.showToast('您已删除该动态', 2000);
  }

  // 点击发布按钮，跳转发布动态页面
  goToIssue() {
    this.router.navigate([`/crowd/dynamic-issue`], {queryParams: {crowdCode: this.params.crowdCode}});
  }

  ngOnInit() {

  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}
